import { createStore } from 'vuex';
import axios from 'axios';

const store = createStore({
    state: {
        isAuthenticated: localStorage.getItem('isAuthenticated') === 'true', // 从 localStorage 初始化状态
        username: localStorage.getItem('username') || '', // 从 localStorage 初始化用户名
        token: localStorage.getItem('token') || '' // 新增 token 状态
    },
    mutations: {
        login(state, payload) {
            state.isAuthenticated = true;
            state.username = payload.username;
            state.token = payload.token;
            localStorage.setItem('isAuthenticated', 'true'); // 保存到 localStorage
            localStorage.setItem('username', payload.username); // 保存用户名
            localStorage.setItem('token', payload.token); // 保存 token
        },
        logout(state) {
            state.isAuthenticated = false;
            state.username = '';
            state.token = '';
            localStorage.removeItem('isAuthenticated'); // 移除 localStorage 数据
            localStorage.removeItem('username'); // 移除用户名
            localStorage.removeItem('token'); // 移除 token
        }
    },
    actions: {
        async login({ commit }, payload) {
            try {
                const response = await axios.post('http://localhost:8080/user/login', {
                    no: payload.username,
                    password: payload.password
                });
                if (response.data.code === 200) {
                    commit('login', { username: payload.username, token: response.data.data });
                    return Promise.resolve();
                } else {
                    return Promise.reject(response.data.msg);
                }
            } catch (error) {
                // 提取更详细的错误信息
                const errorMsg = error.response?.data?.msg || '登录失败';
                return Promise.reject(errorMsg);
            }
        },
        logout({ commit }) {
            commit('logout');
        }
    }
});

export default store;
